<?php
/**
 * User: hadenting
 * Date: 2017/5/10
 * Time: 15:24
 */

namespace backend\controllers;


/**
 * 基于controller-action的权限验证，
 * 权限名称命名规则:$action->controller->id . ucfirst($action->id)
 * 如果controller不需要验证，则不继承此控制器
 * Class BaseValidationController
 * @package backend\controllers
 */
class BaseValidationController extends \common\controllers\BaseController
{
    /**
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        $except_parent_ctrl = [];//父级验证特例控制器，此数组中的控制器不做父级验证，即不做框架验证
        $except_self_ctrl = ['site', 'ajax'];//本页面的权限验证特例控制器，此数组中的控制器不做权限验证
        if (!in_array($action->controller->id, $except_parent_ctrl)) {
            if (!parent::beforeAction($action)) {
                return false;
            }
        }
        if (!in_array($action->controller->id, $except_self_ctrl)) {
            $rules_name = $action->controller->id . ucfirst($action->id);
            if (!\Yii::$app->user->can($rules_name)) {
                \Yii::$app->session->setFlash('warning', '无操作权限');
                $this->redirect(['index']);
                return false;
            }
        }
        return true;
    }

}